package cn.net.wangsu.ssq.controller

import cn.net.wangsu.ssq.dao.SSQHistoryRepository
import cn.net.wangsu.ssq.dao.SSQLuckKeyResultRepository
import cn.net.wangsu.ssq.dao.SSQLuckKeyTempRepository
import cn.net.wangsu.ssq.dao.SSQMD5ResultRepository
import cn.net.wangsu.ssq.models.SsqHistory
import cn.net.wangsu.ssq.models.SsqLuckKeyResult
import cn.net.wangsu.ssq.models.SsqLuckKeyTemp
import cn.net.wangsu.ssq.models.SsqMD5Result
import org.springframework.data.domain.Sort
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import javax.servlet.http.HttpServletResponse

@RestController
class Test(val ssqHistoryRepository: SSQHistoryRepository,
           val ssqmD5ResultRepository: SSQMD5ResultRepository,
           val ssqLuckKeyResultRepository: SSQLuckKeyResultRepository,
           val ssqLuckKeyTempRepository: SSQLuckKeyTempRepository
) {

    val ssqLuckKey = "aaa"

    var stopFlag=true

    @RequestMapping("test")
    fun test(): String {
        return "Hello World"
    }

    @RequestMapping("qall")
    fun qall() = ssqHistoryRepository.findAll()

    @RequestMapping("current")
    fun getCurrent() = ssqLuckKey

    @RequestMapping("luck")
    fun luck() {
        var current = ssqLuckKeyTempRepository.findFirstByOrderByIssueIDDesc()
        var oneData = ssqmD5ResultRepository.findFirstByOrderByIssueIDDesc().get()
        var ssqLuckKeyTemp: SsqLuckKeyTemp
        if (current.isPresent) {
            ssqLuckKeyTemp = current.get()
        } else {
            ssqLuckKeyTemp = SsqLuckKeyTemp(oneData.issueID, "1")
            ssqLuckKeyTempRepository.save(ssqLuckKeyTemp)
        }
        stopFlag=true
        while(stopFlag){
            var luckKey = (ssqLuckKeyTemp.issueID+ssqLuckKeyTemp.luckKey).toByteArray().toMutableList()
            var luck=encode(luckKey.toByteArray())
            if(luck.startsWith(oneData.binaryResult)){
                ssqLuckKeyResultRepository.save(SsqLuckKeyResult(ssqLuckKeyTemp.issueID,ssqLuckKeyTemp.luckKey))
            }
            ssqLuckKeyTemp.luckKey=ssqLuckKeyTemp.luckKey
        }

    }

    @RequestMapping("convert")
    fun convert(response: HttpServletResponse) {
        var allSSQHistory = ssqHistoryRepository.findAll();
        var ssqMD5ResultList: ArrayList<SsqMD5Result> = ArrayList()


        for (ssqhistory in allSSQHistory) {
            var binaryResult = ssqMd5(ssqhistory)
            var ssqMD5Result = SsqMD5Result(ssqhistory)
            ssqMD5Result.binaryResult = binaryResult
            ssqMD5ResultList.add(ssqMD5Result)
            response.writer.write("${ssqMD5ResultList.size}/${allSSQHistory.count()}<br/>")
        }
        ssqmD5ResultRepository.saveAll(ssqMD5ResultList)
        response.writer.write("处理结束")
        response.writer.close()
        //return ssqMD5ResultList.size.toString()
    }

    fun ssqMd5(ssqHistory: SsqHistory): String {
        var sb = StringBuilder()

        sb.append(convertToBinary(ssqHistory.red1));
        sb.append(convertToBinary(ssqHistory.red2));
        sb.append(convertToBinary(ssqHistory.red3));
        sb.append(convertToBinary(ssqHistory.red4));
        sb.append(convertToBinary(ssqHistory.red5));
        sb.append(convertToBinary(ssqHistory.red6));
        sb.append(convertToBinary(ssqHistory.blue));
        return sb.toString()
    }

    fun convertToBinary(data: Short): String {
        var ddstr = data.toString(2)
        if (ddstr.length < 6) {
            ddstr = "00000" + ddstr
            ddstr = ddstr.substring(ddstr.length - 6, ddstr.length)
        }
        return ddstr
    }

    fun encode(moneyCode: ByteArray): String {
        try {
            val instance: MessageDigest = MessageDigest.getInstance("MD5")//获取md5加密对象
            val digest: ByteArray = instance.digest(moneyCode)//对字符串加密，返回字节数组
            var sb = StringBuffer()
            for (b in digest) {
                // b.toByte().toString(2)
                sb.append(b.toUByte().toString(2))
                // var i: Int = b.toInt() and 0xff//获取低八位有效值
                // var hexString = Integer.toBinaryString(i)//将整数转化为16进制
                //if (hexString.length < 2) {
                //    hexString = "0" + hexString//如果是一位的话，补0
                //}
                // sb.append(hexString)
            }
            return sb.toString()

        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }

        return ""
    }

}